//
//  PersonHeadPicture.m
//  timelyRain
//
//  Created by Jiafei Wei on 2016/12/23.
//  Copyright © 2016年 Jiafei Wei. All rights reserved.
//

#import "PersonHeadPicture.h"
#import "HttpTool.h"
#import "NetTools.h"
#import "MJExtension.h"
@implementation UIImage (UIImageExt)

- (UIImage*)imageByScalingAndCroppingForSize:(CGSize)targetSize
{
    UIImage *sourceImage = self;
    UIImage *newImage = nil;
    CGSize imageSize = sourceImage.size;
    CGFloat width = imageSize.width;
    CGFloat height = imageSize.height;
    CGFloat targetWidth = targetSize.width;
    CGFloat targetHeight = targetSize.height;
    CGFloat scaleFactor = 0.0;
    CGFloat scaledWidth = targetWidth;
    CGFloat scaledHeight = targetHeight;
    CGPoint thumbnailPoint = CGPointMake(0.0,0.0);
    if (CGSizeEqualToSize(imageSize, targetSize) == NO)
    {
        NSLog(@"CGSizeEqualToSize");
        CGFloat widthFactor = targetWidth / width;
        CGFloat heightFactor = targetHeight / height;
        if (widthFactor > heightFactor)
            scaleFactor = widthFactor; // scale to fit height
        else
            scaleFactor = heightFactor; // scale to fit width
        scaledWidth= width * scaleFactor;
        scaledHeight = height * scaleFactor;
        // center the image
        if (widthFactor > heightFactor)
        {
            thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;
        }
        else if (widthFactor < heightFactor)
        {
            thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
        }
    }
    UIGraphicsBeginImageContext(targetSize); // this will crop
    CGRect thumbnailRect = CGRectZero;
    thumbnailRect.origin = thumbnailPoint;
    thumbnailRect.size.width= scaledWidth;
    thumbnailRect.size.height = scaledHeight;
    [sourceImage drawInRect:thumbnailRect];
    newImage = UIGraphicsGetImageFromCurrentImageContext();
    if(newImage == nil)
        NSLog(@"could not scale image");
    //pop the context to get back to the default
    UIGraphicsEndImageContext();
    return newImage;
}
@end
@interface PersonHeadPicture ()<UINavigationControllerDelegate,UIImagePickerControllerDelegate>
- (IBAction)changgePic:(id)sender;
@property (weak, nonatomic) IBOutlet UIImageView *headPic;
@property (weak, nonatomic) IBOutlet UIButton *changge;
@property (strong, nonatomic) UIImagePickerController *imagePicker;
@end

@implementation PersonHeadPicture

- (void)viewDidLoad {
    [super viewDidLoad];
    [super setTitleView:self.view withName:@"个人头像"];
    _headPic.layer.masksToBounds=YES;
    _headPic.layer.cornerRadius=_headPic.frame.size.height/2;
    if (_imageUrl!=nil) {
        [_headPic sd_setImageWithURL:[NSURL URLWithString:_imageUrl]];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (IBAction)changgePic:(id)sender {
    if ([NetTools share].isHaveInternet) {
        [self showOkayCancelAlert];
    }else{
        NSLog(@"当前无网络");
    }
}
- (void)showOkayCancelAlert {
    NSString *cancelButtonTitle = @"取消";
    NSString *pic1 =@"拍照上传";
    NSString *pic2 =@"相册上传";
    
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    
    // Create the actions.
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:cancelButtonTitle style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
    }];
    
    UIAlertAction *otherAction = [UIAlertAction actionWithTitle:pic1 style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        //拍照
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            self.imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
            if ([UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceFront]) {
                _imagePicker.cameraDevice = UIImagePickerControllerCameraDeviceFront;
            }
            self.imagePicker.mediaTypes = @[(NSString *)kUTTypeImage];
            [self presentViewController:self.imagePicker animated:YES completion:NULL];
        } else {
            
        }
    }];
    
    UIAlertAction *pic2Action = [UIAlertAction actionWithTitle:pic2 style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        self.imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        self.imagePicker.mediaTypes = @[(NSString *)kUTTypeImage];
        [self presentViewController:self.imagePicker animated:YES completion:NULL];
    }];
    
    // Add the actions.
    [alertController addAction:cancelAction];
    [alertController addAction:otherAction];
    [alertController addAction:pic2Action];
    
    [self presentViewController:alertController animated:YES completion:nil];
}
- (UIImagePickerController *)imagePicker
{
    if (_imagePicker == nil) {
        _imagePicker = [[UIImagePickerController alloc] init];
        _imagePicker.modalPresentationStyle= UIModalPresentationOverFullScreen;
        _imagePicker.allowsEditing = YES;
        _imagePicker.delegate = self;
    }
    
    return _imagePicker;
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [self.imagePicker dismissViewControllerAnimated:YES completion:nil];
}
#pragma mark - UIImagePickerControllerDelegate

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    [self hideHud];
    //[self showHudInView:self.view hint:NSLocalizedString(@"setting.uploading", @"uploading...")];
    
    __weak typeof(self) weakSelf = self;
    UIImage *orgImage = info[UIImagePickerControllerOriginalImage];
    [picker dismissViewControllerAnimated:YES completion:nil];
    if (orgImage) {
        UIImage *img = [orgImage imageByScalingAndCroppingForSize:CGSizeMake(440.f, 440.f)];
        self.headPic.image = img;
        NSData *imgData = UIImagePNGRepresentation(img);
        NSString *doc =[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES)lastObject];
        NSString *plistPath =[doc stringByAppendingPathComponent:@"head.png"];
        [imgData writeToFile:plistPath atomically:YES];
        if ([NetTools share].isHaveInternet) {
            //上传图片
            NSDictionary *pa =@{@"from":@"to",@"to":@"",@"length":@0};
            [HttpTool update:[apiUrl stringByAppendingString:easeUpLoadFile] parameters:pa filePath:plistPath fileName:@"head.png" dataName:@"content" success:^(id responseObject) {
                NSData *jsonData = [NSJSONSerialization dataWithJSONObject:responseObject options:NSJSONWritingPrettyPrinted error:nil];
                NSString *str = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
                NSLog(@"str====上传图片%@",str);
                if ([responseObject objectForKey:@"status"]) {
                    NSDictionary *data =[responseObject objectForKey:@"data"];
                  NSString *fileUrl =  [data objectForKey:@"file_url"];
                    NSLog(@"fileUrl====%@",fileUrl);
                    //返回给过去的值，新的url图像服务器地址不行啊
                    //得到路径
                    NSNotification * notice = [NSNotification notificationWithName:@"setting_data" object:nil userInfo:@{@"type":@"url",@"data":fileUrl}];
                    [[NSNotificationCenter defaultCenter]postNotification:notice];
                }
            } failure:^(NSError *error) {
                
            }];
        }else{
            NSLog(@"当前无网络");
        }
    } else {
        NSLog(@"没有选择了图片啊");
    }
}
-(void)keep{
    
}
@end
